package com.it.emall.service.impl;

import com.it.emall.domain.Recipes;
import com.it.emall.mapper.RecipeMapper;
import com.it.emall.mapper.UserFavoritesMapper;
import com.it.emall.service.UserFavoritesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 收藏
 */
@Service
public class UserFavoritesServiceImpl implements UserFavoritesService {
    @Autowired
    private UserFavoritesMapper userFavoritesMapper;


    /**
     * 检查用户是否已经收藏某个食谱
     * @param userId
     * @param recipeId
     * @return
     */
    @Override
    public int isUserFavoritedRecipe(int userId, int recipeId) {
        System.out.println(recipeId);
        return userFavoritesMapper.isUserFavoritedRecipe(userId,recipeId);
    }

    @Override
    public int toggleFavorite(int userId, int recipeId) {


        // 检查用户是否已经收藏该食谱
        int hasFavorited = userFavoritesMapper.isUserFavoritedRecipe(userId, recipeId);
        if (hasFavorited > 0) {
            // 用户已经收藏，执行取消操作
            int removed = userFavoritesMapper.removeFavorite(userId, recipeId);
            if (removed > 0) {
                System.out.println("❌ 用户取消收藏成功");

                return 1;  // 取消收藏成功
            }
        } else {
            // 用户未收藏，执行收藏操作
            int added = userFavoritesMapper.addFavorite(userId, recipeId);
            if (added > 0) {
                System.out.println("✅ 用户收藏成功");

                return 0;  // 收藏成功
            }
        }
        System.out.println("⚠️ 收藏操作失败");
        return -1;  // 操作失败
    }

    @Override
    public List<Recipes> getUserFavorites(int userId) {
        // 获取用户收藏的食谱列表
        return userFavoritesMapper.findFavoritesByUserId(userId);
    }

    @Override
    public int deleteFavorite(int userId, int recipeId) {
        // 删除用户的收藏
        int result = userFavoritesMapper.removeFavorite(userId, recipeId);
        if (result > 0) {
            System.out.println("✅ 删除收藏成功");
            return 0;  // 删除成功
        }

        System.out.println("⚠️ 删除收藏失败");
        return -1;  // 删除失败

    }
}
